package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author mengwei
 * @date 2019/8/22
 * @desc
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    MenuDao menuDao;

    @Override
    public List<Menu> getMenuList(String username) {
        return menuDao.getMenuList(username);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //设置分页的当前页和每页个数
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //通过查询条件获取分页数据
        Page<Menu> page = menuDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page);
    }

    @Override
    public List<Menu> findChildListById(Integer id) {
        return menuDao.findChildListById(id);
    }

    @Override
    public void add(Menu menu) {
        //给menu中赋值(补全数据)
        //path
        long path = menuDao.findPath();
        menu.setPath(String.valueOf(path + 1));
        //priority
        long priority = menuDao.findPriority();
        menu.setPriority((int) (priority + 1));
        menuDao.add(menu);
    }

    @Override
    public void addChild(Menu menu) {
        //给menu中赋值(补全数据)
        //path
        long path = menuDao.findPathCount(menu.getParentMenuId());
        menu.setPath("/"+menu.getPath()+"-"+String.valueOf(path + 1));
        //priority
        menu.setPriority((int) (path + 1));
        menuDao.addChild(menu);
    }

    @Override
    public void update(Menu menu) {
        menuDao.editMenu(menu);
    }

    @Override
    public void delById(Integer id) {
        //判断主菜单下是否还有子菜单
        long count = menuDao.findCountByParentMenuId(id);
        if (count != 0){
            throw new RuntimeException("主菜单下还有子菜单,不能删除");
        }
        //判断是否和角色中间表有关联
        long roleMenuCount = menuDao.findRoleMenuCountByMenuId(id);
        if (roleMenuCount != 0){
            throw new RuntimeException("和角色中间表有关联,不能删除");
        }
        menuDao.delById(id);
    }

    @Override
    public Menu findMenuChildById(Integer id) {
        return menuDao.findMenuChildById(id);
    }

    @Override
    public void editMenuChild(Menu menu) {
        menuDao.editMenuChild(menu);
    }

    @Override
    public void delChildById(Integer id) {
        //判断是否和角色中间表有关联
        long roleMenuCount = menuDao.findRoleMenuCountByMenuId(id);
        if (roleMenuCount != 0){
            throw new RuntimeException("和角色中间表有关联,不能删除");
        }
        menuDao.delChildById(id);
    }

    @Override
    public List<Menu> findAll() {
        return menuDao.findAll();
    }
}
